package com.ccp.dev.qbdms.service;

import static com.ccp.dev.qbdms.consts.ZhiLiangConst.GROUP_ALREADY_SEND3;
import static com.ccp.dev.qbdms.consts.ZhiLiangConst.GROUP_FAILURE_SEND2;
import static com.ccp.dev.qbdms.consts.ZhiLiangConst.HAIR_DOWN_MAP;

import com.alibaba.fastjson.JSONObject;
import com.ccp.dev.core.basic.base.BaseService;
import com.ccp.dev.core.basic.response.ReturnCode;
import com.ccp.dev.core.basic.util.ContextUtil;
import com.ccp.dev.core.basic.web.query.QueryFilter;
import com.ccp.dev.core.poi.excel.Excel;
import com.ccp.dev.core.util.BeanUtils;
import com.ccp.dev.core.util.StringUtil;
import com.ccp.dev.extend.model.ExtendSysFile;
import com.ccp.dev.extend.service.ExtendSysOrgService;
import com.ccp.dev.form.service.impl.ScriptImpl;
import com.ccp.dev.qbdms.consts.ZhiLiangConst;
import com.ccp.dev.qbdms.dao.WQbdFlightJcDao;
import com.ccp.dev.qbdms.dao.WQbdFlightJczbDao;
import com.ccp.dev.qbdms.model.SysOrgDeploy;
import com.ccp.dev.qbdms.model.WQbdFlightJc;
import com.ccp.dev.qbdms.model.WQbdFlightJczb;
import com.ccp.dev.qbdms.model.WQbdXhdh;
import com.ccp.dev.qbdms.model.vo.WQbdFlightJcGroupVo;
import com.ccp.dev.qbdms.model.vo.WQbdFlightJcLevelSecondVo;
import com.ccp.dev.qbdms.util.BaseUtil;
import com.ccp.dev.qbdms.util.HttpSendUtil;
import com.ccp.dev.qbdms.util.ProjectUUIDUtils;
import com.ccp.dev.qbdms.util.ReadAttachmentUtil;
import com.ccp.dev.system.model.Dictionary;
import com.ccp.dev.system.model.SysOrg;
import com.ccp.dev.system.service.DictionaryService;
import com.ccp.dev.system.service.SysOrgService;
import com.google.common.collect.Maps;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;
import javax.annotation.Resource;
import org.apache.commons.compress.utils.Lists;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.springframework.http.HttpMethod;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;


/**
 * 飞行试验奖惩管理 信息操作服务类
 *
 * @author 于金
 * @date 2020-05-25 16:46:07
 */
@Service
@Transactional(rollbackFor = Exception.class)
public class WQbdFlightJcService extends BaseService<WQbdFlightJc> {
    @Resource
    private WQbdFlightJcDao dao;
    @Resource
    private WQbdFlightJczbDao wQbdFlightJczbDao;
    @Resource
    private WQbdFlightJczbService wQbdFlightJczbService;
    @Resource
    private SysOrgService sysOrgService;
    @Resource
    private ExtendSysOrgService extendSysOrgService;
    @Resource
    private ScriptImpl scriptImpl;
    @Resource
    private WQbdXhdhService wQbdXhdhService;
    @Resource
    private DictionaryService dictionaryService;

    @Resource
    private SysOrgDeployService sysOrgDeployService;

    public HSSFWorkbook exportExcel(Excel excel,QueryFilter queryFilter){
        List<WQbdFlightJc> dataList = this.dao.queryAll(queryFilter);
        int startRow = 1;
        //给每一个单元格赋值
        for (WQbdFlightJc data : dataList) {
            excel.cell(startRow, 0).value(data.getId());
            //excel.cell(startRow, 1).value(data.getMc());
            //可在赋值时，根据需求进行格式化
            //excel.cell(startRow, 2).value(DateFormatUtil.formatDate(data.getRq()));
            //excel.cell(startRow, 3).value(data.getSj());
            //excel.cell(startRow, 4).value(data.getTenantId());
            startRow++;
        }
        return excel.getWorkBook();
    }

    /**
     * 获取反馈数据
     * @param id 参数
     * @return  model
     */
    public WQbdFlightJczb getFeedbackData(String id){
        if(StringUtil.isEmpty(id)){
            return  null;
        }
        List<WQbdXhdh> xhdhList = wQbdXhdhService.getAll();
        //查到子表
        WQbdFlightJczb wQbdFlightJczb = wQbdFlightJczbService.getOneById(id);
        List<Dictionary> dictionaries = dictionaryService.getByNodeKey("ztdwmc");
        if(StringUtil.isNotEmpty(wQbdFlightJczb.getJlswmc())) {
            if(BaseUtil.SystemLevel.GROUPLEVEL.equals(BaseUtil.getCurrentSystemLevel())){
                wQbdFlightJczb.setJlswmcstr(sysOrgService.getSysOrgByOrgCode(wQbdFlightJczb.getJlswmc()).getOrgName());
            }else{
                List<Dictionary> dictionaryList = dictionaries.stream().filter(c->c.getItemValue().equals(wQbdFlightJczb.getJlswmc())).collect(Collectors.toList());
                if(!dictionaryList.isEmpty()){
                    wQbdFlightJczb.setJlswmcstr(dictionaryList.get(0).getItemName());
                }
            }

        }
        //主表数据
        WQbdFlightJc wQbdFlightJc = dao.getById(wQbdFlightJczb.getRefid());
        if(StringUtil.isNotEmpty(wQbdFlightJc.getXhmc())) {
            for(WQbdXhdh xhdh : xhdhList){
                if (xhdh.getId().equals(wQbdFlightJc.getXhmc())) {
                    wQbdFlightJc.setXhmc(xhdh.getfModelname());
                    break;
                }
            }
        }
        if(StringUtil.isNotEmpty(wQbdFlightJc.getZtswmc())){
            if(BaseUtil.SystemLevel.GROUPLEVEL.equals(BaseUtil.getCurrentSystemLevel())){
                wQbdFlightJc.setZtswmcstr(sysOrgService.getSysOrgByOrgCode(wQbdFlightJc.getZtswmc()).getOrgName());
            }else{
                List<Dictionary> dictionaryList = dictionaries.stream().filter(c->c.getItemValue().equals(wQbdFlightJc.getZtswmc())).collect(Collectors.toList());
                if(!dictionaryList.isEmpty()){
                    wQbdFlightJc.setZtswmcstr(dictionaryList.get(0).getItemName());
                }
            }
        }
        wQbdFlightJczb.setwQbdFlightJc(wQbdFlightJc);
        wQbdFlightJczb.setSecret(wQbdFlightJc.getSecret());
        return wQbdFlightJczb;
    }

    @Override
    public int add(WQbdFlightJc wQbdFlightJc) {
        addSubData(wQbdFlightJc);
        return super.add(wQbdFlightJc);
    }

    private void addSubData(WQbdFlightJc WQbdFlightJc) {
        if (BeanUtils.isNotEmpty(WQbdFlightJc.getwQbdFlightJczbList())) {
            if (WQbdFlightJc.getwQbdFlightJczbList().size() > 0) {
                List<WQbdFlightJczb> wQbdFlightJczbs = WQbdFlightJc.getwQbdFlightJczbList();
                ;
                for (WQbdFlightJczb wQbdFlightJczb : wQbdFlightJczbs) {
                    wQbdFlightJczb.setId(ProjectUUIDUtils.getUUIDFor32());
                    wQbdFlightJczb.setRefid(WQbdFlightJc.getId());
                    ZhiLiangConst.addCommonFields(wQbdFlightJczb);
                    wQbdFlightJczb.setReportStatus(ZhiLiangConst.REPORT_STATUS_GROUPTOBEREPORTED);
                }
                wQbdFlightJczbDao.addList(WQbdFlightJc.getwQbdFlightJczbList());
            }
        }
    }

    @Override
    public int update(WQbdFlightJc wQbdFlightJc) {
        wQbdFlightJczbDao.delByRefId(wQbdFlightJc.getId());
        addSubData(wQbdFlightJc);
        return super.update(wQbdFlightJc);
    }

    /**
     * 导出用查询
     *
     * @param queryFilter 查询参数#{tableName,jdbcType=VARCHAR}
     * @return list
     */
    public List<WQbdFlightJc> queryAll(QueryFilter queryFilter) {
        if(BaseUtil.SystemLevel.GROUPLEVEL.equals(BaseUtil.getCurrentSystemLevel())){
            queryFilter.put("tableName","W_QBD_FLIGHT_JCZB_BAK");
        }else {
            queryFilter.put("tableName","W_QBD_FLIGHT_JCZB");
        }
        List<WQbdFlightJc> list =  dao.queryAll(queryFilter);
        List<WQbdXhdh> xhdhList = wQbdXhdhService.getAll();
        List<Dictionary> dictionaries = dictionaryService.getByNodeKey("ztdwmc");
        list.forEach(a->{
            if(StringUtil.isNotEmpty(a.getZtswmc())){
                if(BaseUtil.SystemLevel.GROUPLEVEL.equals(BaseUtil.getCurrentSystemLevel())){
                    SysOrg sysOrg = sysOrgService.getSysOrgByOrgCode(a.getZtswmc());
                    if(BeanUtils.isNotEmpty(sysOrg) && StringUtil.isNotEmpty(sysOrg.getOrgName())){
                        a.setZtswmcstr(sysOrg.getOrgName());
                    }
                }else{
                    List<Dictionary> dictionaryList = dictionaries.stream().filter(c->c.getItemValue().equals(a.getZtswmc())).collect(Collectors.toList());
                    if(!dictionaryList.isEmpty()){
                        a.setZtswmcstr(dictionaryList.get(0).getItemName());
                    }
                }
            }
            if(StringUtil.isNotEmpty(a.getXhmc())) {
                for(WQbdXhdh xhdh : xhdhList){
                    if (xhdh.getId().equals(a.getXhmc())) {
                        a.setXhmc(xhdh.getfModelname());
                        break;
                    }
                }
            }
/*            if(StringUtil.isNotEmpty(a.getStatus())){
                a.setStatusstr(ZhiLiangConst.HAIR_DOWN_MAP.get(a.getStatus()));
            }*/
            List<WQbdFlightJczb> subList = a.getwQbdFlightJczbList();
            subList.forEach(b->{
                if(StringUtil.isNotEmpty(b.getJlswmc())){
                    if(BaseUtil.SystemLevel.GROUPLEVEL.equals(BaseUtil.getCurrentSystemLevel())){
                        SysOrg sysOrg = sysOrgService.getSysOrgByOrgCode(b.getJlswmc());
                        if(BeanUtils.isNotEmpty(sysOrg) && StringUtil.isNotEmpty(sysOrg.getOrgName())){
                            b.setJlswmcstr(sysOrg.getOrgName());
                        }
                    }else{
                        List<Dictionary> dictionaryList = dictionaries.stream().filter(d->d.getItemValue().equals(b.getJlswmc())).collect(Collectors.toList());
                        if(!dictionaryList.isEmpty()){
                            b.setJlswmcstr(dictionaryList.get(0).getItemName());
                        }
                    }
                }
            });
        });
        return list;
    }

    /**
     * 导出用查询
     *
     * @param queryFilter 查询参数
     * @return list
     */
    public List<WQbdFlightJc> queryAllByParams(QueryFilter queryFilter) {
        List<WQbdFlightJc> list = new ArrayList<>();
        queryFilter.addFilter("status", HAIR_DOWN_MAP.get(GROUP_ALREADY_SEND3));
        if(BaseUtil.SystemLevel.GROUPLEVEL.equals(BaseUtil.getCurrentSystemLevel())){
            list = dao.queryAllExportDataGroup(queryFilter);
        }else{
            queryFilter.addFilter("code",extendSysOrgService.getTenOrg(ContextUtil.getCurrentUserId()).getCode());
            list = dao.queryAllExportDataSecond(queryFilter);
        }
        List<WQbdXhdh> xhdhList = wQbdXhdhService.getAll();
        list.forEach(a->{
            if(StringUtil.isNotEmpty(a.getZtswmc())){
                SysOrg sysOrg = sysOrgService.getSysOrgByOrgCode(a.getZtswmc());
                if(BeanUtils.isNotEmpty(sysOrg) && StringUtil.isNotEmpty(sysOrg.getOrgName())){
                    a.setZtswmcstr(sysOrg.getOrgName());
                }
            }
            if(StringUtil.isNotEmpty(a.getXhmc())) {
                for(WQbdXhdh xhdh : xhdhList){
                    if (xhdh.getId().equals(a.getXhmc())) {
                        a.setXhmc(xhdh.getfModelname());
                        break;
                    }
                }
            }
/*            if(StringUtil.isNotEmpty(a.getStatus())){
                a.setStatusstr(ZhiLiangConst.HAIR_DOWN_MAP.get(a.getStatus()));
            }*/
            List<WQbdFlightJczb> subList = a.getwQbdFlightJczbList();
            subList.forEach(b->{
                if(StringUtil.isNotEmpty(b.getJlswmc())) {
                    SysOrg sysOrg = sysOrgService.getSysOrgByOrgCode(b.getJlswmc());
                    if(BeanUtils.isNotEmpty(sysOrg) && StringUtil.isNotEmpty(sysOrg.getOrgName())){
                        b.setJlswmcstr(sysOrg.getOrgName());
                    }
                }
            });
        });
        return list;
    }

    public List<Map> getAllToSubTableList(QueryFilter queryFilter) {
        return dao.getAllToSubTableList(queryFilter);
    }

    public List<WQbdFlightJcGroupVo> groupList(QueryFilter queryFilter) {
        queryFilter.addFilter("status", HAIR_DOWN_MAP.get(GROUP_ALREADY_SEND3));
        List<SysOrg> sysOrgList = extendSysOrgService.getSubLevelOrg();
        sysOrgList = sysOrgList.stream().filter(sysOrg -> sysOrg.getIsTenant() == 1)
            .collect(Collectors.toList());
        List<Dictionary> dicList = new ArrayList<>();
        for (SysOrg sysOrg : sysOrgList) {
            Dictionary dictionary = new Dictionary();
            dictionary.setItemName(sysOrg.getOrgName());
            dictionary.setItemValue(sysOrg.getCode());
            dicList.add(dictionary);
        }
        List<WQbdFlightJcGroupVo> wQbdFlightJcGroupVoList = dao.queryListForGroup(queryFilter);
        Map<String,Object> paramMap= Maps.newHashMap();
        paramMap.put("tableName","W_QBD_FLIGHT_JCZB_BAK");
        for (WQbdFlightJcGroupVo wQbdFlightJcGroupVo : wQbdFlightJcGroupVoList) {
            paramMap.put("refId",wQbdFlightJcGroupVo.getId());
            List<WQbdFlightJczb> wQbdFlightJczbList = wQbdFlightJczbDao
                .getListByRefId(paramMap);
            wQbdFlightJczbList.stream().forEach(wQbdFlightJczb -> {
                try {
                    dicList.forEach(a -> {
                        if (a.getItemValue().equals(wQbdFlightJczb.getJlswmc())) {
                            wQbdFlightJczb.setJlswmc(a.getItemName());
                        }
                    });
                } catch (Exception e) {
                    e.printStackTrace();
                }
            });
            wQbdFlightJcGroupVo.setwQbdFlightJczbList(wQbdFlightJczbList);
        }
        return wQbdFlightJcGroupVoList;
    }

    public List<WQbdFlightJcLevelSecondVo> secondList(QueryFilter queryFilter) {
        queryFilter.addFilter("secret", scriptImpl.getCurrentUser().getPrivacyLevel());
        queryFilter.addFilter("status", HAIR_DOWN_MAP.get(GROUP_ALREADY_SEND3));
        queryFilter.addFilter("code",extendSysOrgService.getTenOrg(ContextUtil.getCurrentUserId()).getCode());
        return dao.queryListForSecond(queryFilter);
    }

    public int updateStatus(List<WQbdFlightJc> list) {
        return dao.updateStatus(list);
    }

    /**
     * 查询上报流程的业务数据
     */
    public List<WQbdFlightJc> reportList(String dataId, String tableName) {
        return dao.reportList(dataId, tableName);
    }

    public int updateBySj(WQbdFlightJc wQbdFlightJc) {
        List<WQbdFlightJc> list = Lists.newArrayList();
        list.add(wQbdFlightJc);
        return dao.updateStatus(list);
    }


    /**
     * 保存接口传输的数据
     *
     * @param wQbdFlightJcList 主表model,有子表的包含子表数据
     * @return
     */
    public void saveAll(List<WQbdFlightJc> wQbdFlightJcList,List<ExtendSysFile> extendSysFileList){
        ReadAttachmentUtil.getEntityData(wQbdFlightJcList,extendSysFileList);
        if (null != wQbdFlightJcList
            && wQbdFlightJcList.size() > 0) {
            for(WQbdFlightJc wQbdFlightJc:wQbdFlightJcList) {
                List<WQbdFlightJczb> wQbdFlightJczbList = wQbdFlightJc.getwQbdFlightJczbList();
                for (WQbdFlightJczb wQbdFlightJczb : wQbdFlightJczbList) {
                    wQbdFlightJczb.setTableName("W_QBD_FLIGHT_JCZB_BAK");
                    wQbdFlightJczbDao.update(wQbdFlightJczb);
                }
            }
        }
    }



    /**
     * 根据主表id查询主表加子表数据
     *
     * @param id 主表id
     * @return
     */
    public WQbdFlightJc getParentAndChilden(String id) {
        WQbdFlightJc wQbdFlightJc=new WQbdFlightJc();
        List<WQbdFlightJczb> wQbdFlightJczbList=Lists.newArrayList();
        wQbdFlightJczbList.add(wQbdFlightJczbDao.getById(id));
        wQbdFlightJc.setwQbdFlightJczbList(wQbdFlightJczbList);
        return wQbdFlightJc;
    }


    /**
     * 下发接口
     * @param list
     * @return
     */
    public boolean reportSend(List<WQbdFlightJc> list) {
        Boolean status=true;
        for (WQbdFlightJc wQbdFlightJc:list){
            //旧的
            List<WQbdFlightJczb> wQbdFlightJczbs = wQbdFlightJc.getwQbdFlightJczbList();
            //新的
            WQbdFlightJc wQbdFlightJc1=new WQbdFlightJc();
            BeanUtils.copyNotNullProperties(wQbdFlightJc1,wQbdFlightJc);
            if(BeanUtils.isNotEmpty(wQbdFlightJc)){
                if (!Children(wQbdFlightJc,wQbdFlightJczbs)){
                    updateParent(wQbdFlightJc1, HAIR_DOWN_MAP.get(GROUP_FAILURE_SEND2));
                    status=false;
                }else {
                    updateParent(wQbdFlightJc1,HAIR_DOWN_MAP.get(GROUP_ALREADY_SEND3));
                }
            }
        }
      return  status;
    }

    /**
     * 判断子表的 下发状态 是否成功
     * @param wQbdFlightJc
     * @param wQbdFlightJczbs
     * @return
     */
    public Boolean Children( WQbdFlightJc wQbdFlightJc,List<WQbdFlightJczb> wQbdFlightJczbs){
        boolean status=true;
        for (WQbdFlightJczb zb : wQbdFlightJczbs) {
            SysOrgDeploy deployMethodByCode = sysOrgDeployService.getDeployMethodByCode(zb.getJlswmc());
            if ((BeanUtils.isNotEmpty(deployMethodByCode) && StringUtil.isNotEmpty(deployMethodByCode.getOrgCode())) && !ZhiLiangConst.DEPMETHOND_CENTER.equals(deployMethodByCode.getDepmethod())) {
                //分级部署 调用接口
                //已下发的就直接不在下发
                if(BeanUtils.isNotEmpty(zb.getStatus())){
                if(zb.getStatus().equals(HAIR_DOWN_MAP.get(GROUP_ALREADY_SEND3))){
                    continue;
                }}
                String url = deployMethodByCode.getUrl();
                url = url + ZhiLiangConst.URL_API + ZhiLiangConst.URL_VERSION + "wQbdFlightJc/reportSend";
                Map<String, Object> map = new HashMap<>(1);
                //只下发一个子表
                List<WQbdFlightJczb> list=new ArrayList<>();
                zb.setStatus(HAIR_DOWN_MAP.get(GROUP_ALREADY_SEND3));
                list.add(zb);
//               给二级及单位传 下发成功的状态
                wQbdFlightJc.setStatus(HAIR_DOWN_MAP.get(GROUP_ALREADY_SEND3));
                wQbdFlightJc.setBelongdeptname(zb.getJlswmc()+".");
                wQbdFlightJc.setwQbdFlightJczbList(list);
                List<WQbdFlightJc> list1=Lists.newArrayList();
                list1.add(wQbdFlightJc);
                map.put(ZhiLiangConst.API_REPORT_PARA_LIST, list1);
                List<ExtendSysFile> extendSysFileList = ReadAttachmentUtil.getReport(map, "WQbdFlightJc");
                if(BeanUtils.isNotEmpty(extendSysFileList)){
                    map.put(ZhiLiangConst.API_REPORT_PARA_LIST_FILE, extendSysFileList);
                }
                try {
                    ResponseEntity<JSONObject> response = HttpSendUtil.httpRestClient(url, HttpMethod.POST, map);
                    if (response.getStatusCode() != HttpStatus.OK || (int) response.getBody().get("code") != ReturnCode.SUCCESS.getCode()) {
                        System.err.println("综合质量分析报告下发服务异常 -> API接口调用失败!");
                        updateChildren(zb, HAIR_DOWN_MAP.get(GROUP_FAILURE_SEND2));
                        status=false;
                    }else{
                        //下发成功
                        updateChildren(zb, HAIR_DOWN_MAP.get(GROUP_ALREADY_SEND3));
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                    System.err.println("综合质量分析报告下发服务异常 -> API接口调用失败!");
                    updateChildren(zb, HAIR_DOWN_MAP.get(GROUP_FAILURE_SEND2));
                    status=false;
                }

            }else{
                //集中部署
//                修改状态为下发成功子表的状态
                 updateChildren(zb,HAIR_DOWN_MAP.get(GROUP_ALREADY_SEND3));

            }
        }

        return status;
    }

    /**
     * 更新父表的状态
     * @param wQbdFlightJc
     * @param status
     * @return
     */
    public int updateParent(WQbdFlightJc wQbdFlightJc,String status) {
        wQbdFlightJc.setStatus(status);
        int result = dao.update(wQbdFlightJc);
        return result;
    }


    /**
     * 更新子表的状态
     * @param wQbdFlightJczb
     * @param status
     * @return
     */
    public int updateChildren(WQbdFlightJczb wQbdFlightJczb,String status) {
        wQbdFlightJczb.setStatus(status);
        wQbdFlightJczb.setReleaseTime(new Date());
        wQbdFlightJczb.setTableName("w_qbd_flight_jczb");
        int result = wQbdFlightJczbDao.update(wQbdFlightJczb);
        return result;
    }

    public int saveSendReport(WQbdFlightJc wQbdFlightJc) {
      return   addSend(wQbdFlightJc);
    }


    public int addSend(WQbdFlightJc wQbdFlightJc) {
        addSubDataSend(wQbdFlightJc);
        return super.add(wQbdFlightJc);
    }

    private void addSubDataSend(WQbdFlightJc WQbdFlightJc) {
        if (BeanUtils.isNotEmpty(WQbdFlightJc.getwQbdFlightJczbList())) {
            if (WQbdFlightJc.getwQbdFlightJczbList().size() > 0) {
                List<WQbdFlightJczb> wQbdFlightJczbs = WQbdFlightJc.getwQbdFlightJczbList();
                for (WQbdFlightJczb wQbdFlightJczb : wQbdFlightJczbs) {
                    wQbdFlightJczb.setReportStatus(ZhiLiangConst.REPORT_STATUS_GROUPTOBEREPORTED);
                }
                wQbdFlightJczbDao.addList(WQbdFlightJc.getwQbdFlightJczbList());
            }
        }
    }
}
